package com.jeeplus.modules.common.excel.common.validator.impl.base;

import com.jeeplus.modules.common.excel.common.anno.base.DataSize;
import com.jeeplus.modules.common.excel.common.validator.abs.AbstractValidator;

import java.lang.reflect.Field;

/**
 * 数据长度校验
 * @author wang.yishu
 */
public class DataSizeValidator extends AbstractValidator {

    private DataSize dataSize;

    @Override
    public boolean canValidate(Field field) {
        dataSize = field.getDeclaredAnnotation(DataSize.class);
        return dataSize != null;
    }

    @Override
    public String toValidate(Object entity, Field field) {
        if (entity == null) return null;
        field.setAccessible(true);
        try {
            Object value = field.get(entity);
            if (value instanceof String) {
                String valueStr = value.toString();
                int max = dataSize.max();
                int min = dataSize.min();
                int length = valueStr.length();
                if (length < min || length > max) {
                    return dataSize.msg();
                }
            } else {
                return null;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }
}
